package com.gc.baselib.img;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Looper;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.gc.baselib.R;
import com.gc.baselib.core.CoreApi;
import com.gc.baselib.utils.ResourceUtils;


import java.io.File;
import java.util.concurrent.ExecutionException;

/**
 *
 */
public class GildeImageLoaderImpl implements IImageLoader{
    @Override
    public void init(Context context) {
        GlideBuilder glideBuilder=new GlideBuilder();
        Glide.init(context,glideBuilder);
    }

    @Override
    public void trimMemory(int level) {
        try {
            if (Looper.myLooper() == Looper.getMainLooper()) {
                Glide.get(CoreApi.getInstance().getContext()).trimMemory(level);
            } else {
                throw new RuntimeException("请在主线程中调用");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void clearMemory() {
        try {
            if (Looper.myLooper() == Looper.getMainLooper()) {
                Glide.get(CoreApi.getInstance().getContext()).clearMemory();
            } else {
                throw new RuntimeException("请在主线程中调用");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void displayImage(ImageLoadConfig builder) {
        RequestManager glideManager=null;

        if(builder.context instanceof Fragment){
            glideManager=Glide.with((Fragment) builder.context);
//            Glide.with((Fragment) builder.context).load(builder.url).into(builder.intoImageView);
        }else if(builder.context instanceof Activity){
            glideManager=Glide.with((Activity) builder.context);
//            Glide.with((Activity) builder.context).load(builder.url).into(builder.intoImageView);
        }else if(builder.context instanceof View){
            glideManager=Glide.with((View) builder.context);
//            Glide.with((Context) builder.context).asFile().load(builder.url).into(builder.intoImageView);

//                GlideUrl glideUrl = new GlideUrl(url, new LazyHeaders.Builder()
//                        .addHeader("Authorization", "ToKen")
//                        .build());
        }
        else if(builder.context instanceof Context){
            glideManager=Glide.with((Context) builder.context);
//            Glide.with((Context) builder.context).asFile().load(builder.url).into(builder.intoImageView);

        }
        if(glideManager==null){
            throw new RuntimeException("Context is error");
        }
        RequestOptions requestOptions=new RequestOptions();
        if(builder.width>0&&builder.height>0){
            requestOptions.override(builder.width,builder.height);
        }

        requestOptions.format(builder.format);
        requestOptions.skipMemoryCache(builder.isSkipCache);
        requestOptions.error(builder.errorholder);
        if(ImageView.ScaleType.CENTER_CROP==builder.scaleType){
            requestOptions.centerCrop();
        }else if(ImageView.ScaleType.FIT_CENTER==builder.scaleType){
            requestOptions.fitCenter();
        }else if(ImageView.ScaleType.CENTER_INSIDE==builder.scaleType){
            requestOptions.centerInside();
        }
        requestOptions.placeholder(builder.placeholder);
        if(builder.tranformation!=null){
            requestOptions.transform(builder.tranformation);
        }
        if(builder.radius>0){
            requestOptions.transform(new CenterCrop(),new RoundedCorners(builder.radius));
        }
        glideManager.setDefaultRequestOptions(requestOptions);

        if(builder.fileType==ImageLoadConfig.FileType.Bitmap){
            RequestBuilder<Bitmap> bitmapGlideRequest=glideManager.asBitmap();
            if(builder.loaderListener!=null){
                bitmapGlideRequest.addListener(new CustomRequestListener<>(builder.loaderListener));
            }
            if(builder.intoImageView==null){
                bitmapGlideRequest.load(builder.url).preload();
            }else{
                bitmapGlideRequest.load(builder.url).into(builder.intoImageView);
            }
        }else if(builder.fileType==ImageLoadConfig.FileType.Gif){
            RequestBuilder<GifDrawable> bitmapGlideRequest=glideManager.asGif();
            if(builder.loaderListener!=null){
                bitmapGlideRequest.addListener(new CustomRequestListener<>(builder.loaderListener));
            }
            if(builder.intoImageView==null){
                bitmapGlideRequest.load(builder.url).preload();
            }else{
                bitmapGlideRequest.load(builder.url).into(builder.intoImageView);
            }
        }else if(builder.fileType==ImageLoadConfig.FileType.Drawable){
            RequestBuilder<Drawable> bitmapGlideRequest=glideManager.asDrawable();
            if(builder.loaderListener!=null){
                bitmapGlideRequest.addListener(new CustomRequestListener<>(builder.loaderListener));
            }
            if(builder.intoImageView==null){
                bitmapGlideRequest.load(builder.url).preload();
            }else{
                bitmapGlideRequest.load(builder.url).into(builder.intoImageView);
            }

        }else if(builder.fileType==ImageLoadConfig.FileType.File){

            RequestBuilder bitmapGlideRequest=glideManager.asFile();
            if(builder.loaderListener!=null){
                bitmapGlideRequest.addListener(new CustomRequestListener<>(builder.loaderListener));
            }
            if(builder.intoImageView==null){
                bitmapGlideRequest.load(builder.url).preload();
            }else{
                bitmapGlideRequest.load(builder.url).into(builder.intoImageView);
            }
        }



    }

    @Override
    public <T> T getImage(ImageLoadConfig builder,T clazz) throws ExecutionException, InterruptedException {
        if(builder.context instanceof Fragment){
            if(clazz instanceof Bitmap){
                return (T)Glide.with((Fragment) builder.context).asBitmap().load(builder.url).submit().get();
            }

        }else if(builder.context instanceof Activity){
            if(clazz instanceof Bitmap) {
                return (T) Glide.with((Activity) builder.context).asBitmap().load(builder.url).submit().get();
            }
        }else if(builder.context instanceof Context){
            if(clazz instanceof Bitmap) {
                return (T) Glide.with((Context) builder.context).asBitmap().load(builder.url).submit().get();
            }

        }
        return null;
    }

    @Override
    public File getCacheDir() {
        return Glide.getPhotoCacheDir(CoreApi.getInstance().getContext());
    }

    @Override
    public void clearDiskCache() {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            throw new RuntimeException(ResourceUtils.getString(R.string.sub_thread_notify));
        } else {
            Glide.get(CoreApi.getInstance().getContext()).clearDiskCache();
        }
    }

    @Override
    public Bitmap getBitmapFromCache(String url) throws ExecutionException, InterruptedException {
        return Glide.with(CoreApi.getInstance().getContext()).asBitmap().onlyRetrieveFromCache(true).load(url).submit().get();
    }

    @Override
    public void getBitmapFromCache(Context context, String url, IGetBitmapListener listener) {
        Glide.with(context).asBitmap().load(url).into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                if (listener != null) {
                    listener.onBitmap(resource);
                }
            }
        });
    }

    @Override
    public void stopLoad(ImageLoadConfig builder) {
        if(builder.context instanceof Fragment){
            Glide.with((Fragment) builder.context).clear(builder.intoImageView);
        }else if(builder.context instanceof Activity){
            Glide.with((Activity) builder.context).clear(builder.intoImageView);
        }else if(builder.context instanceof Context){
            Glide.with((Context) builder.context).clear(builder.intoImageView);
        }

    }

    @Override
    public void pauseRequests(ImageLoadConfig builder) {
        if(builder.context instanceof Fragment){
            Glide.with((Fragment) builder.context).pauseRequests();
        }else if(builder.context instanceof Activity){
            Glide.with((Activity) builder.context).pauseRequests();
        }else if(builder.context instanceof Context){
            Glide.with((Context) builder.context).pauseRequests();
        }
    }

    @Override
    public void resumeRequests(ImageLoadConfig builder) {
        if(builder.context instanceof Fragment){
            Glide.with((Fragment) builder.context).resumeRequests();
        }else if(builder.context instanceof Activity){
            Glide.with((Activity) builder.context).resumeRequests();
        }else if(builder.context instanceof Context){
            Glide.with((Context) builder.context).resumeRequests();
        }
    }

    public class CustomRequestListener<T> implements RequestListener<T>{
        private IImageLoaderListener loaderListener;
        CustomRequestListener (IImageLoaderListener loaderListener){
            this.loaderListener=loaderListener;
        }
        @Override
        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<T> target, boolean isFirstResource) {
            if (loaderListener!=null) {
                return loaderListener.onLoadingFailed(target,e,isFirstResource);
            }
            return false;
        }

        @Override
        public boolean onResourceReady(T resource, Object model, Target<T> target, DataSource dataSource, boolean isFirstResource) {
            if (loaderListener!=null) {
                return loaderListener.onLoadingComplete(target,resource,isFirstResource);
            }
            return false;
        }
    }

}
